package io.renren.common.utils;

import com.alibaba.fastjson.JSON;
import io.renren.common.config.BaseConstant;
import io.renren.common.enums.ErrorCode;
import io.renren.common.exception.RRException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class IdentityUtil {

    @Autowired
    private BaseConstant baseConstant;

    @Value("${baseConstant.idcardVerify.Host}")
    private String host;

    @Value("${baseConstant.idcardVerify.AppCode}")
    private String AppCode;


    public Identity verify(String idCard, String name) {
        String path = "/idcard/VerifyIdcardv2";
        String method = "GET";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + AppCode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("cardNo", idCard);
        querys.put("realName", name);
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            Identity identity = JSON.parseObject(EntityUtils.toString(response.getEntity()), Identity.class);
            if (!identity.getResult().isok) {
                throw new RRException(ErrorCode.VERIFY_FAIL.getMessage(),ErrorCode.VERIFY_FAIL.getCode());
            }
            return identity;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException(ErrorCode.VERIFY_FAIL.getMessage(),ErrorCode.VERIFY_FAIL.getCode());
        }
    }

    @Data
    public static class Identity {
        private int error_code;
        private String reason;
        private ResultBean result;

    }

    @Data
    public static class ResultBean {
        private String realname;
        private String idcard;
        private boolean isok;
        private IdCardInforBean IdCardInfor;
    }

    @Data
    public static class IdCardInforBean {
        private String area;
        private String sex;
        private String birthday;
    }
}
